package com.yzd.learnjava.io;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import com.yzd.learnjava.util.Print;

public class MyWorld implements Serializable {
	public static void main(String[] args) throws Exception {
		House house = new House();
		List<Animal> animals = new ArrayList<Animal>();
		animals.add(new Animal("Bosco the dog", house));
		animals.add(new Animal("Ralph the hamster", house));
		animals.add(new Animal("Molly the cat", house));
		Print.print("Animals : " + animals);
		
		ByteArrayOutputStream bao = new ByteArrayOutputStream();
		ObjectOutputStream o = new ObjectOutputStream(bao);
		o.writeObject(animals);
		o.writeObject(animals);
		
		ByteArrayOutputStream bao2 = new ByteArrayOutputStream();
		ObjectOutputStream o2 = new ObjectOutputStream(bao2);
		o2.writeObject(animals);
		
		ObjectInputStream in1 = new ObjectInputStream(new ByteArrayInputStream(bao.toByteArray()));
		ObjectInputStream in2 = new ObjectInputStream(new ByteArrayInputStream(bao2.toByteArray()));
		
		List animals1 = (List)in1.readObject();
		List animals2 = (List)in1.readObject();
		List animals3 = (List)in2.readObject();
		
		Print.print("animals1 : " + animals1);
		Print.print("animals2 : " + animals2);
		Print.print("animals3 : " + animals3);
		
		
	}
	
}

class House implements Serializable{}
class Animal implements Serializable{
	private String name ;
	private House preferredHouse;
	Animal(String nm, House i){
		name = nm;
		preferredHouse = i;
	}
	
	public String toString() {
		return name + "[" + super.toString() + "], " + preferredHouse + "\n";
	}
}